<template>
  <div>
    <el-dialog title="题目设置" :visible.sync="visible">
      <el-form :model="tableForm" ref="tableForm" :rules="tableRules">
        <el-form-item label="题目" prop="question">
          <el-input
            :disabled="disabled"
            v-model="tableForm.question"
            placeholder="请输入题目"
          ></el-input>
        </el-form-item>
        <el-form-item label="模块" prop="subject">
          <el-select
            v-model="tableForm.subject"
            placeholder="请选择模块"
            :disabled="disabled"
          >
            <el-option
              v-for="item in subjects"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节" prop="chapter">
          <el-select
            v-model="tableForm.chapter"
            placeholder="请选择章节"
            :disabled="disabled"
          >
            <el-option
              v-for="item in chapters"
              :label="item.name"
              :value="item.name"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子章节" prop="subChapter">
          <el-select
            v-model="tableForm.subChapter"
            placeholder="请选择子章节"
            :disabled="disabled"
          >
            <!-- 暂时不设置子章节 -->
          </el-select>
        </el-form-item>
        <el-form-item label="选项A" prop="item1">
          <el-input
            v-model="tableForm.item1"
            placeholder="请输入选项A"
            :disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="选项B" prop="item2">
          <el-input
            v-model="tableForm.item2"
            placeholder="请输入选项B"
            :disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="选项C" prop="item3">
          <el-input
            v-model="tableForm.item3"
            placeholder="请输入选项C"
            :disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="选项D" prop="item4">
          <el-input
            v-model="tableForm.item4"
            placeholder="请输入选项D"
            :disabled="disabled"
          ></el-input>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-select
            multiple
            v-model="tableForm.answer"
            placeholder="请选择答案"
            :disabled="disabled"
          >
            <el-option
              v-for="(item, index) in answer"
              :key="index"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答案解析" prop="remark">
          <el-input
            type="textarea"
            autosize
            v-model="tableForm.remark"
            :disabled="disabled"
            placeholder="答案解析"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="!disabled">
        <el-button @click="resetHandler('tableForm')">重 置</el-button>
        <el-button type="primary" @click="submit('tableForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import questionApi from "@/api/question/index";
import subjectApi from "@/api/subject/index";
import chapterApi from "@/api/chapter/index";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    const validateQuestion = (rule, value, callback) => {
      if (!value) {
        callback(new Error("问题不得为空！"));
      } else {
        let trim = value.trim();
        if (trim == "") {
          callback(new Error("问题不得为空！"));
        } else {
          callback();
        }
      }
    };
    const validateSubject = (rule, value, callback) => {
      if (!value) {
        callback(new Error("所在模块不得为空！"));
      } else if (value == "") {
        callback(new Error("所在模块不得为空！"));
      } else {
        callback();
      }
    };
    const validateChapter = (rule, value, callback) => {
      if (!value) {
        callback(new Error("所在章节不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项1不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项2不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem3 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项3不得为空！"));
      } else {
        callback();
      }
    };
    const validateItem4 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("选项4不得为空！"));
      } else {
        callback();
      }
    };
    const validateAnswer = (rule, value, callback) => {
      if (value.length > 0) {
        callback();
      } else {
        callback(new Error("答案不得为空！"));
      }
    };
    //这里存放数据
    return {
      editFlag: true, //表示提交操作是更新还是添加,true表示更新,false表示添加
      tableForm: {
        question: "",
        subject: "",
        chapter: "",
        subChapter: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
        remark: "",
      },
      answer: ["A", "B", "C", "D"],
      subjects: [],
      chapters: [],
      tableRules: {
        question: [
          {
            require: true,
            trigger: "blur",
            validator: validateQuestion,
          },
        ],
        subject: [
          {
            require: true,
            trigger: "blur",
            validator: validateSubject,
          },
        ],
        chapter: [
          { require: true, validator: validateChapter, trigger: "blur" },
        ],
        subChapter: [{ require: false }],
        item1: [{ required: true, trigger: "blur", validator: validateItem1 }],
        item2: [{ required: true, trigger: "blur", validator: validateItem2 }],
        item3: [{ required: true, trigger: "blur", validator: validateItem3 }],
        item4: [{ required: true, trigger: "blur", validator: validateItem4 }],
        answer: [{ require: true, validator: validateAnswer, trigger: "blur" }],
        remark: [{ require: false }],
      },
    };
  },
  props: {
    disabled: { type: Boolean, default: false },
    questionId: {
      type: Number,
      default: function () {
        return { type: 1 };
      },
    },
    dialogFormVisible: false,
  },
  //计算属性 类似于 data 概念
  computed: {
    visible: {
      get() {
        return this.dialogFormVisible;
      },
      set(value) {
        this.$emit("update:dialogFormVisible", {
          type: "detail",
          val: value,
        });
      },
    },
  },
  //监控 data 中的数据变化
  watch: {
    tableForm: {
      handler(newVal, oldVal) {
        // 监听到 obj 发生变化时的处理逻辑
        this.chapters = [];
        if (newVal.subject) {
          chapterApi.getByName(newVal.subject).then((res) => {
            this.chapters = res.data;
          });
        }
      },
      deep: true, // 开启深度监视
    },
  },
  //方法集合
  methods: {
    submit(tableForm) {
      this.$refs[tableForm].validate((valid) => {
        if (valid) {
          if (this.editFlag) {
            questionApi.update(this.tableForm).then((res) => {
              this.$message({
                message: `${res.message}`,
                type: "success",
              });
              this.$emit("update:dialogFormVisible", {
                type: "detail",
                val: false,
              });
            });
          } else {
            questionApi.add(this.tableForm).then((res) => {
              this.$message({
                message: `${res.message}`,
                type: "success",
              });
              this.$emit("update:dialogFormVisible", {
                type: "detail",
                val: false,
              });
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetHandler(tableForm) {
      this.$refs[tableForm].resetFields();
    },
    init() {
      questionApi.getById(this.questionId).then((res) => {
        const {
          chapter,
          item1,
          item2,
          item3,
          item4,
          question,
          remark,
          subChapter,
          subject,
          id,
        } = res.data;
        this.tableForm = {
          chapter,
          item1,
          item2,
          item3,
          item4,
          question,
          remark,
          subChapter,
          subject,
          id,
        };
        let arr = res.data.answer.split("+");
        this.$set(this.tableForm, "answer", arr);
        this.getSubject();
      });
    },
    getSubject() {
      subjectApi.getAll().then((res) => {
        this.subjects = res.data;
        const res1 = res.data.find(
          (subject) => subject.name == this.tableForm.subject
        );
        if (res1) {
          chapterApi.getBySubjectId(res1.id).then((response) => {
            this.chapters = response.data;
          });
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    console.log(this.disabled);
    if (this.questionId != 0) {
      this.editFlag = true;
      this.init();
    } else {
      this.getSubject();
      this.editFlag = false;
      this.tableForm = {
        question: "",
        subject: "",
        chapter: "",
        subChapter: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
        remark: "",
      };
    }
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
